<template>
  <div>
    <el-dialog
      title="用户注册"
      :visible.sync="isShow"
      width="605px"
      center

      @close="closeEvent"
    >
      <div>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="头像" prop="avatar">
            <el-input v-show="false" v-model="form.avatar" />
            <el-upload
              class="avatar-uploader"
              :action="baseUrl + '/' + '/uploads'"
              name="image"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.avatar" :src="form.avatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item label="昵称" prop="username">
            <el-input v-model.trim="form.username" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model.trim="form.email" />
          </el-form-item>
          <el-form-item label="手机" prop="phone">
            <el-input v-model.trim="form.phone" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model.trim="form.password" show-password />
          </el-form-item>
          <el-form-item label="图形码" prop="code">
            <div class="txm">
              <el-input v-model.trim="form.code" />
              <img
                ref="captcha"
                class="code-img"
                :src="baseUrl + '/captcha?type=sendsms'"
                alt=""
                @click="getCaptcha"
              >
            </div>
          </el-form-item>
          <el-form-item label="验证码" prop="rcode">
            <div class="yzm">
              <el-input v-model.trim="form.rcode" />
              <el-button
                :disabled="disabledstate"
                class="anniu"
                @click="verifiable_code"
              >获取用户验证码<span
                v-if="disabledstate"
              >({{ disabledstatenum }})</span></el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <el-button @click="calloff">取消</el-button>
          <el-button
            size="medium"
            type="primary"
            @click="submit"
          >确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Sendsms, Register } from '@/api/user.js'
export default {
  data() {
    return {
      // 禁用状态布尔值
      disabledstate: false,
      disabledstatenum: 5,
      baseUrl: process.env.VUE_APP_URL,
      isShow: false,
      form: {
        avatar: '', //	是	string	头像地址
        username: '', //	是	string	用户名
        email: '', //	是	string	邮箱
        phone: '', //	是	string	手机号
        password: '', //	是	string	密码
        rcode: '', //	是	string	验证码
        code: ''
      },
      form1: {
        avatar: ''
      },
      rules: {
        avatar: [{ required: true, message: '请上传头像', trigger: 'change' }], //	是	string	头像地址
        username: [
          { required: true, message: '请输入用户名', trigger: 'change' },
          {
            message: '请输入正确的名称',
            trigger: 'change'
          }
        ], //	是	string	用户名
        email: [
          { required: true, message: '请输入邮箱', trigger: 'change' },
          {
            pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.(com|cn)$/,
            message: '请输入正确的邮箱'
          }
        ], //	是	string	邮箱
        phone: [
          { required: true, message: '请输入手机号!', trigger: 'change' },
          {
            pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
            message: '请输入正确的手机号',
            trigger: 'change'
          }
        ], //	是	string	手机号
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          {
            min: 6,
            message: '密码最小6位数',
            trigger: 'change'
          }
        ], //	是	string	密码
        rcode: [
          { required: true, message: '请输入图形码!', trigger: 'change' }
        ], //	是	string	验证码
        code: [
          { required: true, message: '请输入验证码', trigger: 'change' },
          {
            min: 4,
            max: 4,
            message: '验证码长度四位数',
            trigger: 'change'
          }
        ] // 是 验证码
      }
    }
  },
  methods: {
    getCaptcha() {
      this.$refs.captcha.src =
        this.baseUrl + '/captcha?type=sendsms&dfhdfh=' + Date.now()
    },
    // 注册图片上传成功后的回调
    handleAvatarSuccess(res, file) {
      console.log(res)
      // console.log(file)
      if (res.code === 205) {
        return
      }
      this.form.avatar = this.baseUrl + '/' + res.data.file_path
      this.form1.avatar = res.data.file_path
    },
    // 图片上传前的回调,（拿到上传文件的类型大小,限制上传文件与大小）
    beforeAvatarUpload(file) {
      // 上传前的限制
      // file:type size
      console.log(file)
      // 限制文件类型
      const typeArr = ['image/jpeg', 'image/png']
      const typeBol = typeArr.includes(file.type)
      if (!typeBol) {
        this.$message.error('请上传jpg与png图片')
      }
      return typeBol
    },
    // 局部表单验证
    verifiable_code() {
      // this.$refs.form.validateField(['phone', 'code'], async(result) => {
      //   if (result) {
      //     this.$message.success('验证成功')
      //     Sendsms(this.form)
      //   }
      // })
      const results = []
      this.$refs.form.validateField(['phone', 'code'], async(result) => {
        if (!result) {
          results.push(result)
          if (results.length === 2 && results.every((item) => item === '')) {
            // Sendsms(this.form).then((res) => {
            //   console.log(res)
            //   this.$message.success('验证成功')
            // })
            // const form1 = {
            //   code: this.form.code,
            //   phone: this.form.phone
            // }
            this.disabledstatemethod()
            const res = await Sendsms({
              code: this.form.code,
              phone: this.form.phone
            })
            console.log(res)

            // this.$message.success(res.data.data.captcha)
            if (res.data.data.captcha) {
              this.$message.success(`${res.data.data.captcha}`)
            } else {
              this.$message.error(`${res.data.message}`)
            }
          }
        }
      })
    },
    // 注册确定点击
    // 全局表单验证
    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          const res = await Register({
            avatar: this.form1.avatar, //	是	string	头像地址
            username: this.form.username, //	是	string	用户名
            email: this.form.email, //	是	string	邮箱
            phone: this.form.phone, //	是	string	手机号
            password: this.form.password, //	是	string	密码
            rcode: this.form.rcode //	是	string	验证码
          })
          console.log(res)
          if (res.data.data.user_id) {
            this.$message.success('注册成功')
            this.form = {
              avatar: '', //	是	string	头像地址
              username: '', //	是	string	用户名
              email: '', //	是	string	邮箱
              phone: '', //	是	string	手机号
              password: '', //	是	string	密码
              rcode: '', //	是	string	验证码
              code: ''
            }
            this.isShow = false
            this.$refs.form.resetFields()
          } else {
            this.$message.success(res.data.message)
          }
        }
      })
    },
    closeEvent() {
      this.calloff()
    },
    // 注册取消点击
    calloff() {
      this.form = {
        avatar: '', //	是	string	头像地址
        username: '', //	是	string	用户名
        email: '', //	是	string	邮箱
        phone: '', //	是	string	手机号
        password: '', //	是	string	密码
        rcode: '', //	是	string	验证码
        code: ''
      }
      this.isShow = false
      this.$refs.form.resetFields()
    },
    // 封装一个禁用状态函数
    disabledstatemethod() {
      this.disabledstate = true
      const shijian = setInterval(() => {
        this.disabledstatenum--
        if (this.disabledstatenum < 0) {
          this.disabledstate = false
          clearInterval(shijian)
          this.disabledstatenum = 5
        }
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  height: 53px;
  line-height: 25px;
  text-align: center;
  color: #fff;
  background: linear-gradient(90deg, #01c4fa, #1294fa);
  .el-dialog__title {
    color: #fff;
  }
}
::v-deep .el-dialog__close{
  color: #fff;
}
::v-deep .el-dialog__body {
  padding: 30px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
  .avatar-uploader {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .el-upload--text {
    width: 180px;
    height: 180px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .txm {
    display: flex;
  }
  .el-input__inner {
    padding: 0 15px;
  }
  .code-img {
    width: 140px;
    height: 40px;
    margin-left: 4.16667%;
  }
  .yzm {
    display: flex;
  }
  .anniu {
    width: 153px;
    height: 40px;
    margin-left: 4.16667%;
  }
}
</style>
